package com.vpen.account.demo.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vpen.clib.constant.CConstant;
import com.vpen.clib.result.CODE_MSG;
import com.vpen.clib.result.CResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 韦鹏
 * @desc 没有权限处理器
 * @date 2022/7/15 11:56
 **/
@Slf4j
@AllArgsConstructor(onConstructor_ = @Autowired)
@Component
public class AccountDemoAccessDeniedHandler implements AccessDeniedHandler {
    private final ObjectMapper objectMapper;


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.debug(request.getRequestURI() + ": 未授权", accessDeniedException);
        //设置返回请求头
        response.setContentType(CConstant.CONTENT_TYPE);
        //写出流
        PrintWriter out = response.getWriter();
        CResult<String> error = CResult.error(CODE_MSG.FORBIDDEN);
        error.setData(accessDeniedException.getMessage());
        out.write(objectMapper.writeValueAsString(error));
        out.flush();
        out.close();
    }
}
